# 所有和数据库有关的函数方法
# 定义和数据库的连接

# 根据用户名查询用户是否存在的函数
# import the database connection function

import function.python_connect_mysql as fp

# 根据用户名查询用户是否存在的函数
def query_user_no_exists(username):
    conn = fp.get_connection()
    try:
        sql = "SELECT * FROM sys_user WHERE username = %s"
        cur = conn.cursor()
        cur.execute(sql, (username))
        result = cur.fetchone()
        print(result)
        return result is None
    finally:
        cur.close()
        conn.close()

def query_user(username):
    conn = fp.get_connection()
    try:
        sql = "SELECT * FROM sys_user WHERE username = %s"
        cur = conn.cursor()
        cur.execute(sql, [username])
        result = cur.fetchone()
        return result
    finally:
        cur.close()
        conn.close()

# 根据用户名和密码添加数据的函数
def add_user(username, password):
    conn = fp.get_connection()
    try:
        sql = "INSERT INTO sys_user (username, password) VALUES (%s, %s)"
        cur = conn.cursor()
        cur.execute(sql, (username, password))
        conn.commit()
    finally:
        cur.close()
        conn.close()

def Call_Message(user_id):
    conn = fp.get_connection()
    try:
        sql = "SELECT * FROM chat_message WHERE user_id = %s order by message_time asc"
        cur = conn.cursor()
        cur.execute(sql, [user_id])
        result = cur.fetchall()
        return result
    finally:
        cur.close()
        conn.close()